<template>
  <view class="announcement-detail" :style="{ background: themeColorStyles.backgroundGradient }">
    <!-- 内容区域 -->
    <view class="content-container">
      <!-- 公告卡片 -->
      <view class="announcement-card" :style="{ 'box-shadow': `0 8rpx 32rpx ${themeColorStyles.primaryColorShadow}` }">
        <!-- 标题 -->
        <view class="title-section" :style="{ background: `linear-gradient(135deg, ${themeColorStyles.primaryColor} 0%, ${themeColorStyles.primaryColorGlow} 100%)` }">
          <text class="announcement-title">{{ announcementData.title }}</text>
          <view class="title-divider"></view>
        </view>
        
        <!-- 内容 -->
        <view class="content-section">
          <text class="announcement-content">{{ announcementData.content }}</text>
        </view>
        
        <!-- 底部信息 -->
        <view class="info-section" v-if="announcementData.startTime">
          <text class="start-time">开始时间：{{ formatTime(announcementData.startTime) }}</text>
        </view>
      </view>
    </view>
  </view>
</template>

<script>
import { getAnnouncement } from '@/api/announcement'
import { API_CONFIG } from '@/api/config'
import { getThemePrimaryColor, getThemeColorFromGlobal } from '@/utils/theme'

export default {
  data() {
    return {
      announcementId: '',
      announcementData: {
        title: '',
        content: '',
        startTime: ''
      },
      themeColor: '1'
    }
  },
  
  computed: {
    primaryColor() {
      return getThemePrimaryColor(this.themeColor)
    },
    
    themeColorStyles() {
      const primary = this.primaryColor
      const primaryRgb = this.hexToRgb(primary)
      const primaryGlow = this.lightenColor(primary, 20)
      const primaryLight = this.lightenColor(primary, 85)
      
      return {
        '--primary-color': primary,
        primaryColor: primary,
        primaryColorGlow: primaryGlow,
        primaryColorShadow: `rgba(${primaryRgb.r}, ${primaryRgb.g}, ${primaryRgb.b}, 0.15)`,
        backgroundGradient: `linear-gradient(135deg, ${primaryLight} 0%, #F8F9FA 100%)`
      }
    }
  },

  
  async onLoad(options) {
    // 获取主题色
    await this.initThemeColor()
    
    if (options.id) {
      this.announcementId = options.id
      this.loadAnnouncementFromCache()
    } else {
      uni.showToast({
        title: '公告ID不能为空',
        icon: 'error'
      })
      setTimeout(() => {
        uni.navigateBack()
      }, 1500)
    }
  },
  
  async onShow() {
    // 页面显示时重新获取主题色，确保主题色同步
    await this.initThemeColor()
  },
  
  methods: {
    // 初始化主题色
    async initThemeColor() {
      try {
        // 优先从本地存储获取
        let savedTheme = uni.getStorageSync('themeColor')
        
        // 如果本地存储没有，从全局配置获取
        if (!savedTheme) {
          savedTheme = await getThemeColorFromGlobal()
        }
        
        // 设置主题色
        if (savedTheme) {
          this.themeColor = savedTheme
        }
        
        // 强制更新视图
        this.$forceUpdate()
      } catch (error) {
        console.error('获取主题色失败:', error)
        this.themeColor = '1' // 默认主题色
      }
    },
    
    // 从缓存中加载公告数据
      loadAnnouncementFromCache() {
        try {
          // 从单独缓存的公告详情中获取数据，缓存键包含orgId
          const cacheKey = `notice_detail_${this.announcementId}_${API_CONFIG.ORG_ID}`
          const cachedNotice = this.getCacheData(cacheKey)
          
          if (cachedNotice) {
             this.announcementData = {
               title: cachedNotice.title || '系统公告',
               content: cachedNotice.content || '暂无内容',
               startTime: cachedNotice.startTime || ''
             }
            return
          }
          
          // 如果缓存中没有找到，直接尝试API获取
          this.loadAnnouncementDetail()
          
        } catch (error) {
          console.error('从缓存加载公告失败:', error)
          this.loadAnnouncementDetail()
        }
      },
    
    // 加载公告详情
    async loadAnnouncementDetail() {
      try {
        const response = await getAnnouncement(this.announcementId)
        
        if (response.code === 200 && response.data) {
          this.announcementData = {
            title: response.data.title || '系统公告',
            content: response.data.content || '暂无内容',
            startTime: response.data.startTime || ''
          }
        } else {
          // 如果API失败，设置错误信息
           this.announcementData = {
             title: '获取失败',
             content: '暂时无法获取公告内容，请稍后再试。',
             startTime: ''
           }
          uni.showToast({
            title: '获取公告详情失败',
            icon: 'none'
          })
        }
      } catch (error) {
        console.error('获取公告详情失败:', error)
        this.announcementData = {
           title: '获取失败',
           content: '暂时无法获取公告内容，请稍后再试。',
           startTime: ''
         }
        uni.showToast({
          title: '网络错误，请稍后再试',
          icon: 'none'
        })
      }
    },
    
    // 格式化时间
    formatTime(timeStr) {
      if (!timeStr) return ''
      try {
        const date = new Date(timeStr)
        const year = date.getFullYear()
        const month = String(date.getMonth() + 1).padStart(2, '0')
        const day = String(date.getDate()).padStart(2, '0')
        const hours = String(date.getHours()).padStart(2, '0')
        const minutes = String(date.getMinutes()).padStart(2, '0')
        return `${year}-${month}-${day} ${hours}:${minutes}`
      } catch (error) {
        return timeStr
      }
    },
    
    // 获取缓存数据
    getCacheData(key) {
      try {
        const cacheStr = uni.getStorageSync(key)
        if (!cacheStr) return null
        
        // 如果缓存数据已经是对象，直接使用
        let cacheData
        if (typeof cacheStr === 'object') {
          cacheData = cacheStr
        } else if (typeof cacheStr === 'string') {
          cacheData = JSON.parse(cacheStr)
        } else {
          console.warn('缓存数据格式异常:', typeof cacheStr)
          uni.removeStorageSync(key)
          return null
        }
        
        const now = Date.now()
        
        // 检查缓存是否过期（10分钟）
        if (cacheData.timestamp && now - cacheData.timestamp > 10 * 60 * 1000) {
          uni.removeStorageSync(key)
          return null
        }
        
        return cacheData.data || cacheData
      } catch (error) {
        console.error('获取缓存失败:', error)
        // 清除损坏的缓存
        uni.removeStorageSync(key)
        return null
      }
    },
    
    // 将十六进制颜色转换为RGB
    hexToRgb(hex) {
      const result = /^#?([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})$/i.exec(hex)
      return result ? {
        r: parseInt(result[1], 16),
        g: parseInt(result[2], 16),
        b: parseInt(result[3], 16)
      } : { r: 0, g: 122, b: 255 }
    },
    
    // 颜色变亮
    lightenColor(color, percent) {
      const rgb = this.hexToRgb(color)
      const factor = percent / 100
      const r = Math.round(rgb.r + (255 - rgb.r) * factor)
      const g = Math.round(rgb.g + (255 - rgb.g) * factor)
      const b = Math.round(rgb.b + (255 - rgb.b) * factor)
      return `rgb(${r}, ${g}, ${b})`
    }
  }
}
</script>

<style lang="scss" scoped>
.announcement-detail {
  min-height: 100vh;
}

.content-container {
  padding: 32rpx 32rpx 40rpx;
}

.announcement-card {
  background: #FFFFFF;
  border-radius: 24rpx;
  overflow: hidden;
  margin-bottom: 32rpx;
}

.title-section {
  padding: 40rpx 32rpx 24rpx;
  position: relative;
}

.announcement-title {
  font-size: 36rpx;
  font-weight: 600;
  color: #FFFFFF;
  line-height: 1.4;
  display: block;
}

.title-divider {
  width: 60rpx;
  height: 6rpx;
  background: rgba(255, 255, 255, 0.8);
  border-radius: 3rpx;
  margin-top: 16rpx;
}

.content-section {
  padding: 40rpx 32rpx;
}

.announcement-content {
  font-size: 30rpx;
  color: #333333;
  line-height: 1.8;
  display: block;
  white-space: pre-wrap;
  word-break: break-word;
}

.info-section {
  padding: 24rpx 32rpx 32rpx;
  border-top: 2rpx solid #F5F5F5;
  background: #FAFAFA;
}

.start-time {
  font-size: 24rpx;
  color: #999999;
  display: block;
}

/* 响应式适配 */
@media screen and (max-width: 750rpx) {
  .content-container {
    padding: 100rpx 24rpx 40rpx;
  }
  
  .announcement-title {
    font-size: 32rpx;
  }
  
  .announcement-content {
    font-size: 28rpx;
  }
}
</style>